<?php

namespace App\Admin\Controllers;

use App\Models\DeviceInfo;
use App\Models\DeviceType;
use App\Models\AreaInfo;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use Log;

use App\Services\DeviceInfoService;

use App\Admin\Actions\Post\OpenAllPost;
use App\Admin\Actions\Post\CloseAllPost;

class DeviceInfoController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '设备管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {

        $grid = new Grid(new DeviceInfo);
        $grid->paginate(35);

        $grid->filter(function($filter){
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            // $filter->expand();
            $filter->column(1/4, function ($filter) {
                $filter->like('code', '编号');
            });
            // 在这里添加字段过滤器
            $filter->column(1/4, function ($filter) {
                $filter->like('name', '设备名称');
            });
            $filter->column(1/4, function ($filter) {
                $filter->like('type', '设备类型');
            });
            $filter->column(1/4, function ($filter) {
                $filter->like('area', '区域');
            });
            
        });

        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new OpenAllPost());
            $tools->append(new CloseAllPost());
        });


        $grid->column('id', __('Id'));
        $grid->column('code', __('设备编码'));
        $grid->column('name', __('设备名称'));
        $grid->column('type', __('设备类型'))->display(function ($type) {
            return DeviceType::where(['id'=>$type])->pluck('name')[0];
        });
        $grid->column('area', __('区域'))->display(function ($area) {
            return AreaInfo::where(['id'=>$area])->pluck('name')[0];
        });
        $grid->column('desc', __('描述'));
        $grid->column('cmd', __('指令'));
        $grid->column('status', __('状态'))->using(['11' => '<span style="color:red">关</span>', '12' => '<span style="color:green">开</span>'], '未知');

        $grid->column('enable', __('状态'))->using(['0' => '无效', '1' => '有效'], '未知');

        // $grid->column('', __('开关操作'))->display(function () {
        //     return "<a class='btn btn-success btn-sm grid-row-on' data-id='{$this}'>开</a>    <a class='btn btn-danger btn-sm grid-row-off' data-id='{$this}'>关</a>";
        // });

        $grid->column(' ', __('开关操作'))->display(function () {
            if ($this['status'] == '11') {
                return "<a class='btn btn-success btn-sm grid-row-on' data-id='{$this}'>开启</a>";
            } else {
                return "<a class='btn btn-danger btn-sm grid-row-off' data-id='{$this}'>关闭</a>";
            }
        });

        $grid->column('updated_at', __('Updated at'));

        $this->script = <<<EOT

        //open all
        $('.openall-posts').unbind('click').click(function() {
            swal({
                title: "确认打开全部的电源吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {

                    var row_on = $(".grid-row-on");
                    console.log(row_on.length);
                    var i = 0;
                    var t = setInterval(function(){
                        // console.log($(row_on[i]).data('id'));
                        var _id = $(row_on[i]).data('id').id;
                        var _name = $(row_on[i]).data('id').name;
                        var _cmd = $(row_on[i]).data('id').cmd;
                        $.ajax({
                            method: 'get',
                            url: '/api/sentCmd?id=' + _id + '&flag=12&cmd=' + _cmd,
                            success: function (data) {
                                // console.log(data);
                                var o = eval("(" + data + ")");  // 转换为json对象
                                // console.log(o.code);
                                
                                if(o.code == '200') {
                                    $.admin.toastr.success('打开' + _name + '的电源成功！', '', {positionClass:"toast-top-center"});
                                }else{
                                    $.admin.toastr.error('打开' + _name + '的电源失败！', '', {positionClass:"toast-top-center"});
                                }
                                

                            }
                        }); 
                        i += 1;
                        if(i > row_on.length - 1){
                            clearInterval(t);
                            $.pjax.reload('#pjax-container');
                        }
                    },5000);
                }
            });
        });

        //open all
        $('.closeall-posts').unbind('click').click(function() {
            swal({
                title: "确认关闭全部的电源吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'get',
                        url: '/api/controlAll?flag=11',
                        success: function (data) {
                            console.log(data);
                            var o = eval("(" + data + ")");  // 转换为json对象
                            console.log(o.code);
                            
                            if(o.code == '200') {
                                swal('关闭全部电源成功！', '', 'success');
                            }else{
                                swal('关闭全部电源失败！', '', 'error');
                            }
                            $.pjax.reload('#pjax-container');

                        }
                    });
                }
            });
        });

        $('.grid-row-on').unbind('click').click(function() {
            console.log($(this).data('id'));
            // console.log($(this).data('id').name);
            // console.log($(this).data('id').cmd);
            var _id = $(this).data('id').id;
            var _name = $(this).data('id').name;
            var _cmd = $(this).data('id').cmd;
            swal({
                title: "确认打开" + _name + "的电源吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'get',
                        url: '/api/sentCmd?id=' + _id + '&flag=12&cmd=' + _cmd,
                        success: function (data) {
                            console.log(data);
                            var o = eval("(" + data + ")");  // 转换为json对象
                            console.log(o.code);
                            
                            if(o.code == '200') {
                                swal('打开' + _name + '的电源成功！', '', 'success');
                            }else{
                                swal('打开' + _name + '的电源失败！', '', 'error');
                            }
                            $.pjax.reload('#pjax-container');

                        }
                    });
                }
            });
        });

        $('.grid-row-off').unbind('click').click(function() {
            // console.log($(this).data('id'));
            // console.log($(this).data('id').name);
            // console.log($(this).data('id').cmd);
            var _id = $(this).data('id').id;
            var _name = $(this).data('id').name;
            var _cmd = $(this).data('id').cmd;
            swal({
                title: "确认关闭" + _name + "的电源吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'get',
                        url: '/api/sentCmd?id=' + _id + '&flag=11&cmd=' + _cmd,
                        success: function (data) {
                            console.log(data);
                            var o = eval("(" + data + ")");  // 转换为json对象
                            console.log(o.code);
                            
                            if(o.code == '200') {
                                swal('关闭' + _name + '的电源成功！', '', 'success');
                            }else{
                                swal('关闭' + _name + '的电源失败！', '', 'error');
                            }
                            $.pjax.reload('#pjax-container');
                        }
                    });
                }
            });
        });
EOT;

        Admin::script($this->script);

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(DeviceInfo::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('code', __('Code'));
        $show->field('name', __('Name'));
        $show->field('type', __('Type'));
        $show->field('area', __('Area'));
        $show->field('desc', __('Desc'));
        $show->field('cmd', __('Cmd'));
        $show->field('status', __('Status'));
        $show->field('enable', __('Enable'));
        $show->field('updated_at', __('Updated at'));
        $show->field('created_at', __('Created at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new DeviceInfo);

        $form->text('code', __('编码'))->rules('required');
        $form->text('name', __('名称'))->rules('required');

        $form->select('type','类型')->options(
            DeviceType::get()->pluck('name' , 'id')   
        )->rules('required');

        $form->select('area','区域')->options(
            AreaInfo::get()->pluck('name' , 'id')   
        )->rules('required');

        $form->text('desc', __('描述'));
        $form->text('cmd', __('指令'))->rules('required');

        return $form;
    }
}
